package com.nhim.cms.dao;

// default package

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import com.nhim.cms.dao.IElementDefinitionDAO;
import com.nhim.cms.domain.ElementDefinition;
import com.nhim.core.dao.CoreDAO;

/**
 * A data access object (DAO) providing persistence and search support for
 * ElementDefinition entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .ElementDefinition
 * @author Huy Lieu TA
 */
@Repository
public class ElementDefinitionDAO extends CoreDAO<Integer, ElementDefinition>
		implements IElementDefinitionDAO {
	// property constants
	public static final String ALLOW_EDIT = "allowEdit";
	public static final String DEFAULT_VALUE = "defaultValue";
	public static final String IS_METADATA = "isMetadata";
	public static final String IS_SEARCHABLE = "isSearchable";
	public static final String NAME = "name";
	public static final String DESCRIPTION = "description";
	public static final String DEFINITION_TEXT = "definitionText";
	public static final String ELEMENT_TYPE = "elementType";

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}

	/**
	 * Find all ElementDefinition entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the ElementDefinition property to query
	 * @param value
	 *            the property value to match
	 * @return List<ElementDefinition> found by query
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<ElementDefinition> findByProperty(String propertyName,
			final Object value) {
		logger.debug("finding ElementDefinition instance with property: "
				+ propertyName + ", value: " + value);
		try {
			final String queryString = "select model from ElementDefinition model where model."
					+ propertyName + "= :propertyValue";
			return getJpaTemplate().executeFind(new JpaCallback() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = em.createQuery(queryString);
					query.setParameter("propertyValue", value);
					return query.getResultList();
				}
			});
		} catch (RuntimeException re) {
			logger.error("find by property name failed", re);
			throw re;
		}
	}

	public static ElementDefinitionDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (ElementDefinitionDAO) ctx.getBean(ElementDefinitionDAO.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ElementDefinition> getAvailableElementDefinition(
			final Integer contentTypeId) {
		try {
			final String queryString = "select model from ElementDefinition model where model not in "
					+ "( select CTED.ElementDefinition  from ContentTypeElementDefinition CTED where CTED.ContentType.Id"
					+ " = :propertyValue";
			return getJpaTemplate().executeFind(
					new JpaCallback<List<ElementDefinition>>() {

						@Override
						public List<ElementDefinition> doInJpa(EntityManager em)
								throws PersistenceException {
							Query query = em.createQuery(queryString);
							query.setParameter("propertyValue", contentTypeId);
							return query.getResultList();

						}
					});
		} catch (RuntimeException re) {
			logger.error(
					"get available element definition for content type Id: "
							+ contentTypeId + "failed", re);
			throw re;
		}

	}

	public Integer countElementDefinitionsBySearch(final String startsWith) {
		try {
			return getJpaTemplate().execute(new JpaCallback<Integer>() {

				@Override
				public Integer doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = queryElementDefinitionsBySearch(em,
							startsWith, null, true);
					return ((Number) query.getSingleResult()).intValue();
				}
			});
		} catch (RuntimeException re) {
			logger.error("countElementDefinitionsBySearch failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<ElementDefinition> findElementDefinitionEntriesBySearch(
			final String startsWith, final String orderBy) {

		try {
			return getJpaTemplate().executeFind(
					new JpaCallback<List<ElementDefinition>>() {

						@Override
						public List<ElementDefinition> doInJpa(EntityManager em)
								throws PersistenceException {
							Query query = queryElementDefinitionsBySearch(em,
									startsWith, orderBy, false);
							return query.getResultList();
						}
					});
		} catch (RuntimeException re) {
			logger.error("findElementDefinitionEntriesBySearch failed", re);
			throw re;
		}

	}

	/**
	 * Query for Element Definitions based on the search parameters. If
	 * startsWith is specified, the results will not be ordered.
	 * 
	 * @param startsWith
	 *            the starting string
	 * @param orderBy
	 *            the order of the results
	 * @param isCount
	 *            true to query on the count only
	 * @return the query, or null to return full report count.
	 */
	private Query queryElementDefinitionsBySearch(EntityManager em,
			String startsWith, String orderBy, boolean isCount) {
		// Determine which parameters to include.
		boolean isFirstStatement = true;
		boolean hasStartsWith = startsWith != null && startsWith.length() > 0;

		// Construct the query string.
		String retValue = isCount ? "count(o)" : "o";
		String queryString = "select " + retValue + " from ElementDefinition o";

		if (hasStartsWith) {
			queryString += isFirstStatement ? " WHERE" : " AND";
			isFirstStatement = false;
			queryString += " o.name >=:startsWith";
			queryString += " AND o.name <=:startsWithZ";
		}
		if (!hasStartsWith && orderBy != null && orderBy.length() >= 0) {
			queryString += " ORDER BY " + orderBy;
		}

		// Construct the query;
		Query query = em.createQuery(queryString);

		if (hasStartsWith) {
			String startsWithLc = startsWith.toLowerCase();
			query.setParameter("startsWith", startsWithLc);
			query.setParameter("startsWithZ", startsWithLc + "zzzzzz");
		}
		return query;
	}

	@Override
	public ElementDefinition findByName(String name) {
		List<ElementDefinition> result = findByProperty(NAME,name);
		if(result.size() > 0)
			return result.get(0);
		return null;
	}

}